package com.vinny.springbootflowable2.service;

import com.vinny.springbootflowable2.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(readOnly = true)
    public SysUser login(String loginName, String password) {
        String sql = "SELECT user_id, login_name, user_name, email, phone, gender, password, " +
                    "status, department, position FROM sys_user WHERE login_name = ? AND password = ?";
        try {
            return jdbcTemplate.queryForObject(sql, 
                (rs, rowNum) -> {
                    SysUser user = new SysUser();
                    user.setUserId(rs.getString("user_id"));
                    user.setLoginName(rs.getString("login_name"));
                    user.setUserName(rs.getString("user_name"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                    user.setGender(rs.getString("gender"));
                    user.setPassword(rs.getString("password"));
                    user.setStatus(rs.getString("status"));
                    user.setDepartment(rs.getString("department"));
                    user.setPosition(rs.getString("position"));
                    return user;
                },
                loginName, password);
        } catch (Exception e) {
            return null;
        }
    }

    @Transactional(readOnly = true)
    public SysUser getUserById(String userId) {
        String sql = "SELECT user_id, login_name, user_name, email, phone, gender, password, " +
                    "status, department, position FROM sys_user WHERE user_id = ?";
        try {
            return jdbcTemplate.queryForObject(sql, 
                (rs, rowNum) -> {
                    SysUser user = new SysUser();
                    user.setUserId(rs.getString("user_id"));
                    user.setLoginName(rs.getString("login_name"));
                    user.setUserName(rs.getString("user_name"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                    user.setGender(rs.getString("gender"));
                    user.setPassword(rs.getString("password"));
                    user.setStatus(rs.getString("status"));
                    user.setDepartment(rs.getString("department"));
                    user.setPosition(rs.getString("position"));
                    return user;
                },
                userId);
        } catch (Exception e) {
            return null;
        }
    }
} 